//
//  BSLNativeUI.m
//  Chamleon-template
//
//  Created by YLW on 15/10/21.
//
//

#import "BSLNativeUI.h"
#import "NavigationViewController.h"
#import "UIView+Extension.h"

#define kUIScreenWidth [UIScreen mainScreen].bounds.size.width
#define kUIScreenHeight [UIScreen mainScreen].bounds.size.height



@implementation NativeUIInfo

- (instancetype)init
{
    if (self = [super init])
    {
        self.message = @"变色龙默认message";
        self.title = @"变色龙默认title";
        self.buttonCapture = @"按钮内容";
    }
    return self;
}

- (BOOL)isVersion8
{
    return _isVersion8 =[[UIDevice currentDevice].systemVersion floatValue] >= 8.0;
}

@end

@interface BSLNativeUI ()<UITextFieldDelegate,UIActionSheetDelegate,UIAlertViewDelegate>

@end

@implementation BSLNativeUI


#pragma mark - 弹出输入对话框
- (void)prompt:(CDVInvokedUrlCommand *)command
{
    self.callbackID = command.callbackId;
    self.nativeUI.state = NATIVEUISTATEINPUT;
    
    self.nativeUI.title = [command argumentAtIndex:0 withDefault:nil];
    self.nativeUI.message = [command argumentAtIndex:1 withDefault:nil];
    self.nativeUI.tip = [command argumentAtIndex:2 withDefault:nil];
    self.nativeUI.buttonCaptures = [command argumentAtIndex:3 withDefault:nil];
    
    if (self.nativeUI.isVersion8)
    {
        [self createPrompt];
        return;
    }
    
    [self createPromptVersion7];
}

- (void)createPrompt
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"输入提示框" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    for (int i = 0 ; i < self.nativeUI.buttonCaptures.count; i++)
    {
        if (i == 0)
        {
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:self.nativeUI.buttonCaptures[i] style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
                [self sendPromptMessage:i];
            }];
            [alertVC addAction:cancel];
            continue;
        }
        UIAlertAction *action = [UIAlertAction actionWithTitle:self.nativeUI.buttonCaptures[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self sendPromptMessage:i];
            
        }];
        [alertVC addAction:action];
    }
    
    [alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = self.nativeUI.tip;
        textField.delegate = self;
    }];
    
    [self.viewController presentViewController:alertVC animated:YES completion:nil];
}

- (void)createPromptVersion7
{
    UIAlertView *promptView = [[UIAlertView alloc] initWithTitle:@"输入提示框" message:@"" delegate:self cancelButtonTitle:self.nativeUI.buttonCaptures[0] otherButtonTitles:nil, nil];
    
    [promptView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    
    for (int i = 0 ; i < self.nativeUI.buttonCaptures.count; i++)
    {
        if (i == 0) continue;
        [promptView addButtonWithTitle:self.nativeUI.buttonCaptures[i]];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChenge:) name:UITextFieldTextDidChangeNotification object:nil];
    
    [promptView show];
}

- (void)sendPromptMessage:(int)index
{
    NSMutableDictionary *event = [NSMutableDictionary dictionary];
    
    [event setObject:[NSNumber numberWithInt:index] forKey:@"index"];
    [event setObject:self.nativeUI.textFiledStr == nil ? @"" : self.nativeUI.textFiledStr forKey:@"value"];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:event];
    
    [self.commandDelegate sendPluginResult:result callbackId:self.callbackID];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    self.nativeUI.textFiledStr = textField.text;
    return YES;
}

#pragma mark - 弹出时间选择器
- (void)pickTime:(CDVInvokedUrlCommand *)command
{
    self.callbackID = command.callbackId;
    
    [self createPickView:PickDateViewStyleTime];

}
#pragma mark - 弹出日期选择器
- (void)pickDate:(CDVInvokedUrlCommand *)command
{
    self.callbackID = command.callbackId;

    [self createPickView:PickDateViewStyleDate];
}

- (void)createPickView:(PickDateViewStyle)style
{

    NavigationViewController *nav =  [NavigationViewController sharedInstance];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight - 202)];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [nav.view addSubview:btn];
    
    PickDateView *dateView = [PickDateView sharedPickDateView];
    
    dateView.frame = CGRectMake(0, kUIScreenHeight, kUIScreenWidth, 162 + 40);
    [nav.view addSubview:dateView];
    
    [UIView animateWithDuration:0.5 animations:^{
        dateView.y = [UIScreen mainScreen].bounds.size.height - 202;
    }];
    dateView.style = style;
    self.pickDateView = dateView;
    dateView.disMissPickDateViewBlock = ^(NSInteger index,NSDate *date){
        CDVPluginResult *result = nil;
        if (index)
        {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = style == PickDateViewStyleDate ? @"yyyy-MM-dd":@"HH:mm:ss";
            NSString *dateStr = [formatter stringFromDate:date];
            result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:dateStr];
        }
        else
        {
            NSMutableDictionary *error = [NSMutableDictionary dictionary];
            [error setObject:@[@0] forKey:@"code"];
            [error setObject:@"用户取消" forKey:@"message"];
            result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:error];
        }
        
        [self.commandDelegate sendPluginResult:result callbackId:self.callbackID];
        [UIView animateWithDuration:0.5 animations:^{
            self.pickDateView.y = [UIScreen mainScreen].bounds.size.height;
        } completion:^(BOOL finished) {
            [self.pickDateView removeFromSuperview];
            [btn removeFromSuperview];
        }];
    };
}

- (void)btnClick:(UIButton *)btn
{
    if (self.nativeUI.state ==NATIVEUISTATEWAIT ) {
        [btn removeFromSuperview];
        [self.waitingView removeFromSuperview];
        self.waitingView = nil;
        return;
    }
    [UIView animateWithDuration:0.5 animations:^{
        self.pickDateView.y = [UIScreen mainScreen].bounds.size.height;
    } completion:^(BOOL finished) {
        [self.pickDateView removeFromSuperview];
        [btn removeFromSuperview];
    }];

}
#pragma mark - 弹出系统选择按钮框
- (void)actionSheet:(CDVInvokedUrlCommand *)command
{
    self.callbackID = command.callbackId;
    
    self.nativeUI.state = NATIVEUISTATESHEET;
    
    self.nativeUI.title = [command argumentAtIndex:0 withDefault:nil];
    
    self.nativeUI.buttonCaptures = [command argumentAtIndex:1 withDefault:nil];
    
    self.nativeUI.message = nil;
    
    
    if (self.nativeUI.isVersion8)
    {
        [self createAlert];
        return;
    }
    
    [self createAlertVersion7];
}
#pragma mark - 弹出等待对话框
- (void)showWaiting:(CDVInvokedUrlCommand *)command
{
    self.callbackID = command.callbackId;
    self.nativeUI.state = NATIVEUISTATEWAIT;
    NSDictionary *waitingOptions = [command argumentAtIndex:0 withDefault:nil];
    [self.nativeUIWaitInfo setNativeUIWaitInfo:waitingOptions];
    NSLog(@"%@",self.nativeUIWaitInfo);
    
    NavigationViewController *nav =  [NavigationViewController sharedInstance];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight)];
    btn.backgroundColor = [UIColor blackColor];
    btn.alpha = 0.5;
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [nav.view addSubview:btn];
    
    WaitingView *waitingView = [WaitingView sharedWaitingView];
    self.waitingView = waitingView;
    [nav.view addSubview:waitingView];
    waitingView.viewInfo = self.nativeUIWaitInfo;
    
    waitingView.disMissVc = ^(){
        [btn removeFromSuperview];
        [self.waitingView removeFromSuperview];
        self.waitingView = nil;
    };
    
}


#pragma  mark - 弹出系统提示对话框
- (void)alert:(CDVInvokedUrlCommand *)command
{
    self.callbackID = command.callbackId;
    
    self.nativeUI.state = NATIVEUISTATEALERT;
    
    NSString *message = [command argumentAtIndex:0 withDefault:nil];
    [self setAttributeValues:message attributeStr:@"message"];
    
    NSString *title = [command argumentAtIndex:1 withDefault:nil];
    [self setAttributeValues:title attributeStr:@"title"];
    
    NSString *buttonCapture = [command argumentAtIndex:2 withDefault:nil];
    [self setAttributeValues:buttonCapture attributeStr:@"buttonCapture"];
    
    if (self.nativeUI.isVersion8)
    {
        [self createAlert];
        return;
    }
    
    
    [self createAlertVersion7];
    
}


#pragma mark - 弹出系统确认对话框
- (void)confirm:(CDVInvokedUrlCommand *)command
{
    self.callbackID = command.callbackId;
    self.nativeUI.state = NATIVEUISTATESURE;

    NSString *message = [command argumentAtIndex:0 withDefault:nil];
    [self setAttributeValues:message attributeStr:@"message"];
    
    NSString *title = [command argumentAtIndex:1 withDefault:nil];
    [self setAttributeValues:title attributeStr:@"title"];
    
    NSArray *buttonCaptures = [command argumentAtIndex:2 withDefault:nil];
    [self setAttributeValues:buttonCaptures attributeStr:@"buttonCaptures"];
    
    if (self.nativeUI.isVersion8)
    {
        [self createAlert];
        return;
    }

    [self createAlertVersion7];
}

- (void)createAlert
{
    UIAlertControllerStyle style;
    
    if (self.nativeUI.state == NATIVEUISTATESHEET)
    {
        style = UIAlertControllerStyleActionSheet;
    }
    else
    {
        style = UIAlertControllerStyleAlert;
    }
    

    UIAlertController *controller = [UIAlertController alertControllerWithTitle:self.nativeUI.title message:self.nativeUI.message preferredStyle:style];


    if (self.nativeUI.state == NATIVEUISTATEALERT)
    {
        UIAlertAction *action = [UIAlertAction actionWithTitle:self.nativeUI.buttonCapture style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self alertViewClickedButtonAtIndex:0];
        }];
        [controller addAction:action];
    }
    else if (self.nativeUI.state == NATIVEUISTATESURE|| self.nativeUI.state == NATIVEUISTATESHEET)
    {
        for (int i = 0 ; i < self.nativeUI.buttonCaptures.count; i++)
        {
            if (i == 0)
            {
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:self.nativeUI.buttonCaptures[i] style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    [self alertViewClickedButtonAtIndex:i];
                }];
                [controller addAction:cancel];
                continue;
            }
            UIAlertAction *action = [UIAlertAction actionWithTitle:self.nativeUI.buttonCaptures[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self alertViewClickedButtonAtIndex:i];
            }];
            [controller addAction:action];
        }
    }

    [self.viewController presentViewController:controller animated:YES completion:^{
        
    }];

    
}

- (void)alertViewClickedButtonAtIndex:(int)buttonIndex {
    if (self.nativeUI.state == NATIVEUISTATESHEET)
    {
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:buttonIndex];
        
        [self.commandDelegate sendPluginResult:result callbackId:self.callbackID];
        return;
    }
    NSMutableDictionary *options = [NSMutableDictionary dictionary];
    
    [options setObject:[NSNumber numberWithInteger:buttonIndex] forKey:@"isSure"];
    
    NSString *stateStr = [self getNativeUIState:self.nativeUI.state];
    
    [options setObject:stateStr forKey:@"state"];
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:options];
    
    [self.commandDelegate sendPluginResult:result callbackId:self.callbackID];
}


- (void)createAlertVersion7
{
    
    UIAlertView *alertView = nil;
    UIActionSheet *sheet = nil;
    
    if (self.nativeUI.state == NATIVEUISTATEALERT)
    {
        
        alertView = [[UIAlertView alloc] initWithTitle:self.nativeUI.title message:self.nativeUI.message delegate:self cancelButtonTitle:nil otherButtonTitles:self.nativeUI.buttonCapture, nil];
        [alertView show];
    }
    else if (self.nativeUI.state == NATIVEUISTATESURE)
    {
        alertView = [[UIAlertView alloc] initWithTitle:self.nativeUI.title message:self.nativeUI.message delegate:self cancelButtonTitle:self.nativeUI.buttonCaptures[0] otherButtonTitles:nil, nil, nil];
        for (int i = 0 ; i < self.nativeUI.buttonCaptures.count; i++)
        {
            if (i == 0) continue;
            [alertView addButtonWithTitle:self.nativeUI.buttonCaptures[i]];
        }
        
        [alertView show];
    }
    else if (self.nativeUI.state == NATIVEUISTATESHEET)
    {
        sheet = [[UIActionSheet alloc] initWithTitle:self.nativeUI.title delegate:self cancelButtonTitle:self.nativeUI.buttonCaptures[0] destructiveButtonTitle:nil otherButtonTitles:nil, nil];
        for (int i = 0 ; i < self.nativeUI.buttonCaptures.count; i++)
        {
            if (i == 0) continue;
            [sheet addButtonWithTitle:self.nativeUI.buttonCaptures[i]];
        }
        
        [sheet showInView:self.viewController.view];
    }
    
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (self.nativeUI.state == NATIVEUISTATEINPUT)
    {
        [self sendPromptMessage:(int)buttonIndex];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
        return;
    }
    [self alertViewClickedButtonAtIndex:(int)buttonIndex];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self alertViewClickedButtonAtIndex:(int)buttonIndex];
}

- (NSString *)getNativeUIState:(NativeUIState)state
{
    switch (state)
    {
        case NATIVEUISTATEALERT:
            return @"警告提示";
        case NATIVEUISTATESURE:
            return @"系统确认对话框";
        case NATIVEUISTATEWAIT:
            return @"系统等待对话框";
        case NATIVEUISTATEDATE:
            return @"系统日期选择对话框";
        case NATIVEUISTATETIME:
            return @"系统时间选择对话框";
        case NATIVEUISTATEINPUT:
            return @"系统输入对话框";
        default:
            return @"系统默认";
    }
    
}


- (void)setAttributeValues:(id)value attributeStr:(NSString *)attributeStr
{
    if (value) {
        [self.nativeUI setValue:value forKeyPath:attributeStr];
    }
}


- (NativeUIInfo *)nativeUI
{
    if (_nativeUI ==nil)
    {
        _nativeUI = [[NativeUIInfo alloc] init];
        
    }
    return _nativeUI;
}

- (NativeUIWaitInfo *)nativeUIWaitInfo
{
    
    if (_nativeUIWaitInfo == nil)
    {
        _nativeUIWaitInfo = [[NativeUIWaitInfo alloc] init];
    }
    return _nativeUIWaitInfo;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

@end
